const execSQL = require("../../db/mysql");
const md5 = require("md5-node");
async function checkUserName(username) {
    let sql = "select * from user where username=?";
    let sqlParams = [username];
    const data = await execSQL(sql, sqlParams);

    if (data.length === 0) {
        return false;
    } else {
        return true;
    }
}
async function login(user) {
    try {
        if ((await checkUserName(user.name)) === true) {
            let sql = "select * from user where username=? and password=?";

            let sqlParams = [user.name, md5(user.password)];
            const data = await execSQL(sql, sqlParams);
            if (data.length !== 0) {
                return {
                    code: 1,
                    msg: "登陆成功",
                    result: data[0],
                };
            } else {
                return {
                    code: 0,
                    msg: "用户名或密码错误",
                };
            }
        } else {
            return {
                code: 0,
                msg: "用户名不存在",
            };
        }
    } catch (error) {
        return {
            code: 0,
            msg: "error",
        };
    }
}
async function register(user) {
    try {
        let sql =
            "insert into user(username,password,usertype,tel,email,userstate) values(?,?,?,?,?,?)";
        let sqlParams = [
            user.name,
            md5(user.password),
            1,
            user.telephone,
            user.email,
            1,
        ];
        const data = await execSQL(sql, sqlParams);
        return {
            code: 1,
            msg: "注册成功",
        };
    } catch (error) {
        return {
            code: 0,
            msg: "注册失败",
        };
    }
}

module.exports = {
    login,
    register,
    checkUserName,
};
